var app = getApp();
import { CategoryModel } from '../../models/CategoryModel.js'
let shopcart = new CategoryModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopcartData: [], //购物车数据
    ids: [], //购物车id
    count: 0, //商品总数量
    total: 0, //总金额
    balance: 2000, //余额
    address:{},
    addressIndex: 0, //地址下标
    hiddenmodalput: true, //订单备注
    show2: false, //支付弹框
    areaid:'',//地区id
    tag: ['家', '公司','学校','其他'],
    payType:'',//余额/微信 0:2
    ordersn:'',//订单号
    judge:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    console.log(options)
    //截取参数
    var ids = options.id.split('@');
    console.log(ids)
    that.getShopcartById(ids);
    that.address_check()
    that.setData({
      ids: ids,
    })
  },

  getShopcartById:function(type){
    var that = this
    //加载提示
    wx.showLoading({
      title: '加载中...'
    })
    shopcart.getShopcartById(type, data => {
      wx.hideLoading();
      console.log(data)
      let res = data.result.data.data
      that.sum(res)
      that.setData({
        shopcartData:res
      })
    })
  },
  // 查询购物车地址
  address_check:function(){
    var that = this
    shopcart.getAdress(res=>{
      console.log(res)
      let data = res.result.data.data
      for(var i=0;i<data.length;i++){
        if(data[i].default == 1){
          that.setData({
            address: data[i],
            areaid:data[i].poiVal,
          })
          return;
        }
      }
      that.setData({
        addressIndex: -1, //地址下标
      })
    })
  },
  //提交订单按钮
  showBuyModal() {
      let that = this
      //如果没有选择地址，则不能提交订单
      if (this.data.addressIndex === -1) {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none',
          duration: 2000
        })
        return;
      }
      console.log('可以提交')
      // if (wx.getStorageSync("cartGoodIds")) {
      //     this.getUserInfos()
      // } else {
      //     this.getUserInfo()
      // }
      let shopcartData = that.data.shopcartData
      console.log(shopcartData)
      let ids = []
      shopcartData.forEach(item => {
        ids.push(item._id)
      });

            //生成订单编号, 利用时间戳实现编号
            //一个订单编号对应多个商品
            let date = new Date();
            let orderNo = 'NO' + date.getTime();
            console.log('orderNo ==> ', orderNo);

            //订单时间,不足十，补零
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            month = month >= 10 ? month : '0' + month;
            let d = date.getDate();
            d = d >= 10 ? d : '0' + d;
            let hour = date.getHours();
            hour = hour >= 10 ? hour : '0' + hour;
            let minute = date.getMinutes();
            minute = minute >= 10 ? minute : '0' + minute;
            let second = date.getSeconds();
            second = second >= 10 ? second : '0' + second;
            let orderDate = year + '-' + month + '-' + d + ' ' + hour + ':'
            + minute + ':' + second;


            let address = that.data.address;
            let userAddress = {
              address: address.region[1] + address.region[2] + address.detail,
              tag:address.tag,
              phone: address.phone,
              user: address.user
            };  
            //保存订单数据
            let orderData = {
              id:orderNo, //订单编号
              userAddress: userAddress, //地址数据
              orderDate:orderDate, //订单时间
              products:[],//商品
              remark:that.data.name//备注
            };
            console.log(orderData)
      
      shopcartData.forEach(v => {
        orderData.products.push(v)
      })
      console.log(ids)
      console.log(orderData)
      that.setData({
        show2: true,
        payType:'0',
      })



      that.generate_order(orderData, ids)
  },
  generate_order:function(order, ids){
    let that = this
    shopcart.addOrder(order, data => {
      console.log(data)
      if(data.result.data.errMsg == "collection.add:ok"){

        that.setData({
          show2: true,
          payType:'0',
        })

        //删除数据库购物车数据
        shopcart.removeShopcart(ids, res => {
          console.log(res)
        })

      }
    })
  },

  addAddress: function () {
    wx.navigateTo({
      url: "../address/address"
    })
  },
  signEvent: function(e){
    console.log(e)
    this.setData({
      show2:false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this

    if(app.globalData.address == true){
      var address = wx.getStorageSync('address')
      that.setData({
        address: address,
        addressIndex:address.index
      })
      app.globalData.address = false
      console.log(that.data.addressIndex)
    }

    //如果 isBack 为 true，就返回上一页
    if(that.data.isBack) {
        wx.navigateBack()
    }
  },
    //计算总金额
    sum: function (res) {
      //获取勾选的商品计算总金额
      var total = 0;
      res.forEach(v => {
          total += v.num * v.price;
      })
      this.setData({
        total: total
      })
    },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
    //订单备注 
    bindName(e) {
      this.setData({
        name: e.detail.value
      })
    },
    modalinput: function () {
      this.setData({
        hiddenmodalput: !this.data.hiddenmodalput
      })
    },
    //取消按钮 
    cancel: function () {
      this.setData({
        hiddenmodalput: true
      });
    },
    //确认 
    confirm: function () {
      this.setData({
        hiddenmodalput: true
      })
    },
})